#!/usr/bin/env python

#############################################################################
# Author: Enrico Trotta <enrico.trt@gmail.com>
#############################################################################
# 
# pyWebcheck is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################


import gtk
import gtk.glade
import pygtk
from ftplib import FTP
import os
import filecmp
import MessageBox 
from sys import exit
import gobject

try: 
	from pynotify import *
except: 
	ImportError

pygtk.require("2.0")

first_time_notification = True # this checks if the connection notification is showed one time

class ftp_conn:

	def save_dir(self, mode):
		if mode == 1: # update the directory tree
			self.dat = []
			self.ftp.dir(self.dat.append)
			self.file_list = open(".list","wb")
			for x in self.dat:
				self.file_list.write(x + "\n")
			self.file_list.close()

		elif mode == 2: # get the new directory tree to compare
			self.file_list_new = open(".list_new","w")
			self.data_compare = []
			self.ftp.dir(self.data_compare.append)
			self.file_list_new = open(".list_new","wb")
			for x in self.data_compare:
				self.file_list_new.write(x + "\n")
			self.file_list_new.close()

	def compare_file(self):
		uri_refresh = "file://" + os.path.abspath(os.path.curdir) + "/../data/icons/refresh.png"
		if filecmp.cmp(".list",".list_new") == False:
			if init("cmp False"):
				cmp_false = Notification("pyWebcheck", "Alcuni file sono stati aggiornati.", uri_refresh)
				cmp_false.set_timeout(2500)
				cmp_false.show()
				if check_autoupdate.get_active() == True:
					save_dir(1)
			else: 
				exit("Impossibile inizializzare il modulo pynotify.")
	
	def check_server(self):
		self.value_spin = spin_button.get_value_as_int() * 60000 # convert in milliseconds
		self.save_dir(2)
		self.compare_file()
		if self.value_spin != 0:
			gobject.timeout_add(self.value_spin, self.check_server)

	def connect(self):
		self.host = hostname.get_text()
		uri_online = "file://" + os.path.abspath(os.path.curdir) + "/../data/icons/online.png"
		try: 
			self.ftp = FTP(hostname.get_text())
			self.ftp.login(username.get_text(), password.get_text())
			if init("Connection OK"):
				conn_ok = Notification("pyWebcheck", "Connessione stabilita con successo con %s." % self.host, uri_online)
				conn_ok.set_timeout(2500)
				conn_ok.show()
			else: 
				exit("Impossibile inizializzare il modulo pynotify.")	
		except: 
			if (hostname.get_text() == '' or username.get_text() == '' or password.get_text == ''):
				messageBox.run(window1, "Errore", "Devi compilare tutti i campi richiesti per la connessione.")
				messageBox.destroy()
			else: 
				messageBox.run(window1, "Errore", "Impossibile eseguire la connessione.")
				messageBox.destroy() 
		
		if first_time == True:
			self.save_dir(1)

		self.check_server()	
	
	def refresh(self):
		uri_refresh = "file://" + os.path.abspath(os.path.curdir) + "/../data/icons/refresh.png"
		try:
			self.save_dir(1)
			if init("Refresh OK"):
				drefresh = Notification("pyWebcheck", "La lista dei file sul server %s e' stata aggiornata." % self.host, uri_refresh)
				drefresh.set_timeout(1500)
				drefresh.show()	
			else:
				exit("Impossibile inizializzare il modulo pynotify.")
		except:
			messageBox.run(window1, "Errore", "Impossibile aggiornare la lista di file. Probabilmente non e' possibile collegarsi al server.")
			messageBox.destroy() 
	

	def quit(self):
		uri_offline = "file://" + os.path.abspath(os.path.curdir) + "/../data/icons/offline.png"
		try:
			self.ftp.quit()
			if init("Disconnection OK"):
				dconn_ok = Notification("pyWebcheck", "Disconnessione eseguita con successo da %s." % self.host, uri_offline)
				dconn_ok.set_timeout(1500)
				dconn_ok.show()
			else: 
				exit("Impossibile inizializzare il modulo pynotify.")
		except:
			messageBox.run(window1, "Errore", "Non e' stata stabilita nessuna conessione da interrompere.")
			messageBox.destroy() 

					
class Widgets:
	
	def clean1_clicked_cb(widget, data=None):
		hostname.set_text("")
	def clean2_clicked_cb(widget, data=None): 
		username.set_text("")
	def clean3_clicked_cb(widget, data=None): 
		password.set_text("")
	def imagemenuitem10_activate_cb(widget, data=None):
		about.run()
		about.destroy()
	def pulisci_menu_activate_cb(widget, data=None):
		hostname.set_text("")
		username.set_text("")
		password.set_text("")
	def check_welcome_toggled_cb(widget, data=None):
		welcome_message = 1
	def options_window_show(widget, data=None):
		expander.activate()
		
def button1_clicked_cb(widget, data=None):
	ftp_.connect()
	if check_welcome.get_active() == True:
		print ftp_.ftp.getwelcome()
	tray.set_tooltip("Connesso con %s." % hostname.get_text())

def button2_clicked_cb(widget, data=None):
	ftp_.quit()

def button3_clicked_cb(widget, data=None):
	window1.destroy()

def button4_clicked_cb(widgets, data=None):
	ftp_.refresh()

def on_window1_destroy(widget, data=None):
  	gtk.main_quit() 


def on_status_icon_right_clicked(widget, button, event_t):
         popupMenu = gtk.Menu()
         menuPopup1 = gtk.ImageMenuItem (gtk.STOCK_CONNECT)
         popupMenu.add(menuPopup1)
	 menuPopup1.connect("activate", button1_clicked_cb)
         menuPopup2 = gtk.ImageMenuItem (gtk.STOCK_DISCONNECT)
         popupMenu.add(menuPopup2)
	 menuPopup2.connect("activate", button2_clicked_cb)
	 menuPopup3 = gtk.ImageMenuItem (gtk.STOCK_REFRESH)
         popupMenu.add(menuPopup3)
	 menuPopup3.connect("activate", button4_clicked_cb)
	 separator = gtk.SeparatorMenuItem()
         popupMenu.append(separator)
	 menuPopup4 = gtk.ImageMenuItem (gtk.STOCK_QUIT)
         popupMenu.add(menuPopup4)
	 menuPopup4.connect("activate", button3_clicked_cb)
         popupMenu.show_all()
	 popupMenu.popup(None, None, None, button, event_t)



# Dichiarazione dell classi

ftp_ = ftp_conn()
widgets = Widgets()
messageBox = MessageBox.messagebox()

signal = {
	'on_window1_destroy': on_window1_destroy,
  	'button1_clicked_cb': button1_clicked_cb,
  	'button2_clicked_cb': button2_clicked_cb,
  	'button3_clicked_cb': button3_clicked_cb,
	'button4_clicked_cb': button4_clicked_cb,
	'clean1_clicked_cb': widgets.clean1_clicked_cb,
	'clean2_clicked_cb': widgets.clean2_clicked_cb,
	'clean3_clicked_cb': widgets.clean3_clicked_cb,
	'imagemenuitem10_activate_cb': widgets.imagemenuitem10_activate_cb,
	'pulisci_menu_activate_cb': widgets.pulisci_menu_activate_cb,
	'check_welcome_toggled_cb': widgets.check_welcome_toggled_cb,
	'options_window_show': widgets.options_window_show
}

gladeFile = gtk.glade.XML('../data/ui/UI.glade')
window1 = gladeFile.get_widget('window1')
about = gladeFile.get_widget('aboutdialog')
gladeFile.signal_autoconnect(signal)

tray = gtk.StatusIcon()
tray.set_from_file('../data/icons/logo.png')
tray.set_visible(True)
tray.connect('popup-menu', on_status_icon_right_clicked)


first_time = False

hostname = gladeFile.get_widget('hostname')
username = gladeFile.get_widget('username')
password = gladeFile.get_widget('password')
expander = gladeFile.get_widget('expander1')
check_welcome = gladeFile.get_widget('check_welcome')
check_autoupdate = gladeFile.get_widget('check_updates')
spin_button = gladeFile.get_widget('spinbutton1')

if os.path.exists(".list") == False:
	messageBox.run(window1, "Informazione", "Sembra sia la prima volta che avvii pyWebcheck.\n"
				"Da questo momento verranno creati i file di configurazione e"
				"potrai utilizzare le funzioni del software.")
	messageBox.destroy()
	first_time = True
	file_list = open(".list","w")

if window1: 
	window1.show()
	gtk.main()
